package com.bruce.downloader.util;

import com.bruce.downloader.builder.RestTemplateBuilder;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

/**
 * http客户机工具类
 * <br>CreateDate  2021/09/15 16:26:44
 *
 * @author luotuan
 * @version 1.0.0
 */
public class HttpClientUtils {
    /**
     * 获取RestTemplate
     *
     * @param connectTimeout 连接超时
     * @param readTimeout    读取超时
     * @return RestTemplate
     * <br>CreateDate 2021/09/15 16:27:00
     * @author luotuan
     * @since 1.0.0
     **/
    public static RestTemplate getRestTemplate(int connectTimeout, int readTimeout) {
        return RestTemplateBuilder.builder().setConnectTimeout(connectTimeout).setReadTimeout(readTimeout).build();
    }

    /**
     * 获取RestTemplate
     *
     * @return RestTemplate
     * <br>CreateDate 2021/09/15 16:27:09
     * @author luotuan
     * @since 1.0.0
     **/
    public static RestTemplate getRestTemplate() {
        return RestTemplateBuilder.builder().build();
    }

    /**
     * 获取文件名称
     *
     * @param url        url
     * @param httpHeader http报头
     * @return 文件名称
     * <br>CreateDate 2021/09/15 16:36:28
     * @author luotuan
     * @since 1.0.0
     **/
    public static String getFileName(String url, HttpHeaders httpHeader) {
        String fileName = url.substring(url.lastIndexOf("/")+1);
        if (fileName.contains(".")) {
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (suffix.length() > 4 || suffix.contains("?")) {
                getFileNameByHeader(httpHeader);
            }
        } else {
            getFileNameByHeader(httpHeader);
        }
        return fileName;
    }

    private static String getFileNameByHeader(HttpHeaders httpHeaders) {
        String fileName = httpHeaders.getContentDisposition().getFilename();
        if (StringUtils.isBlank(fileName)) {
            return UUID.randomUUID().toString();
        }
        return fileName;
    }

    /**
     * 得到文件的名称
     *
     * @param url url
     * @return
     * <br>CreateDate 2021/09/15 16:36:36
     * @author luotuan
     * @since 1.0.0
     **/
    public static String getFileNameSimple(String url) {
        return url.substring(url.lastIndexOf("/"));
    }
}
